package com.yuan.controller;

import com.yuan.entity.User;
import com.yuan.enums.ResponseEnum;
import com.yuan.service.UserService;
import com.yuan.util.JWTUtil;
import com.yuan.vo.ResponseVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
public class WebController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseVO login(@RequestParam("account") String account, @RequestParam("password") String password) {
        try {
            User user = userService.findByAccount(account);
            if (user.getPassword().equals(password)) {
                return ResponseVO.success(JWTUtil.sign(account, password));
            } else {
                return ResponseVO.error(ResponseEnum.INCORRECT_CREDENTIALS);
            }
        } catch (Throwable e) {
            return ResponseVO.error(ResponseEnum.ERROR);
        }
    }

    @GetMapping("/needLogin")
    @RequiresAuthentication
    public ResponseVO needLogin() {
        return ResponseVO.error(ResponseEnum.NOT_LOGIN_IN);
    }

    @GetMapping("/index")
    public ResponseVO article() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return ResponseVO.success("You are already logged in ");
        }
        return ResponseVO.success("You are guest");
    }

    @GetMapping("/auth")
    @RequiresAuthentication
    public ResponseVO requireAuth() {
        return ResponseVO.success("You are authenticated");
    }

    @GetMapping("/role")
    @RequiresRoles("vip")
    public ResponseVO requireRole() {
        return ResponseVO.success("You are visiting require_role");
    }

    @GetMapping("/permission")
    @RequiresPermissions(logical = Logical.AND, value = {"add", "update"})
    public ResponseVO requirePermission() {
        return ResponseVO.success("You are visiting permission view and edit");
    }

    @RequestMapping("/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseVO unauthorized() {
        return ResponseVO.error(ResponseEnum.UNAUTHORIZED);
    }
}
